package springboot.listenConsumer;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Optional;
/*
* 该类用于监听发布者发布的消息是否到达了交换机
* 如果未到达可以做相关的操作
* */
@Slf4j
@Component
public class ConfirmMessageCallback implements RabbitTemplate.ConfirmCallback,
    RabbitTemplate.ReturnCallback{
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void initBean(){
        /*将监听重写的类注入至原先的类中*/
        //交换机发布确认消息注入
        rabbitTemplate.setConfirmCallback(this);
        //队列回退消息注入
        rabbitTemplate.setReturnCallback(this);
    }
    /*
    * CorrelationData correlationData这个是消息发布者发送的
    *用来标记消息的唯一标识
    * */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String id=Optional.ofNullable(correlationData).map(CorrelationData::getId).orElse(null);
        if (ack){
            log.info("消息已经发送至交换机,id:{}",id);
        }else {
            log.info("消息发送至交换机失败,id:{},原因:{}",id,cause);
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

    }
}
